import React, { Component } from 'react';
import { connect } from 'react-redux';
import QueueAnim from 'rc-queue-anim';

import DrawCard from '../components/DrawCard';

import msg from '../api/connectMsg';
import { getRoomList, changeRoom, addRoom, subRoom, getRoomInfo } from '../reducers/modules/drawInfo';

@connect(state => state
  , { getRoomList, changeRoom, addRoom, subRoom, getRoomInfo })
class RoomList extends Component {
  constructor(props) {
    super(props);
    this.enterRoom = this.enterRoom.bind(this);
  }

  componentDidMount() {
    this.props.getRoomList(rst => {
      console.log('初始化rommList', rst);
    });

    var socket = window.socket;
    socket.on(msg.ADD_ROOM, rst => {
      console.log('服务器推送新的房间', rst);
      if (rst.code === 1)
        this.props.addRoom(rst.data);

    });

    socket.on(msg.REMOVE_ROOM, rst => {
      console.log('服务器推送移除房间', rst);
      if (rst.code === 1) {
        this.props.subRoom(rst.data);
      }

    });

    socket.on(msg.GET_ROOM_INFO_CHANGE, rst => {
      console.log('房间人员变动', rst);
      this.props.changeRoom(rst);
    });

  }
  componentWillUnmount() {
    //取消监听.
    window.socket.off(msg.ADD_ROOM);
    window.socket.off(msg.REMOVE_ROOM);
    window.socket.off(msg.GET_ROOM_INFO_CHANGE);
  }

  enterRoom(key) {
    console.log('进入房间' + key);
    let drawInfo = this.props.drawInfo.drawInfo;
    if (drawInfo == null || drawInfo.key !== key) {
      console.log('重新获取', drawInfo, key);
      this.props.getRoomInfo(key, rst => {
        this.props.switchSelectTab();
      });
    } else {
      this.props.switchSelectTab();
    }
  }

  render() {
    var list = this.props.drawInfo.drawList.map(t => {
      return <DrawCard
        item={t}
        key={t.key}
        enterRoom={this.enterRoom}
      />
    });

    return (
      <QueueAnim delay={100}>
        {list}
      </QueueAnim>
    );

  }
}
export default RoomList;
